import { createSlice, nanoid, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

const billsSlice = createSlice({
	name: 'bills',
	//数据状态state
	initialState: {
		billsList: [],
		status: 'idle',
		error: null
	},
	reducers: {
		addBill: (state, action) => {
			state.billsList.push({
				id: nanoid(),
				...action.payload
			})
		},
		setBillList: (state, action) => {
			state.billsList = action.payload
		}
	},
	extraReducers(builder) {
		builder
			.addCase(asyncGetBill.pending, (state) => {
				state.status = 'loading'
			})
			.addCase(asyncGetBill.fulfilled, (state, action) => {
				state.status = 'succeeded'
				state.billsList = action.payload
			})
			.addCase(asyncGetBill.rejected, (state, action) => {
				state.status = 'failed'
				state.error = action.error.message
			})
			.addCase(asyncAddNewBill.pending, (state) => {
				state.status = 'loading'
			})
			.addCase(asyncAddNewBill.fulfilled, (state, action) => {
				state.status = 'succeeded'
				state.billsList.push(action.payload)
			})
			.addCase(asyncAddNewBill.rejected, (state, action) => {
				state.status = 'failed'
				state.error = action.error.message
			})
	}
})

export const { addBill, setBillList } = billsSlice.actions

export const asyncGetBill = createAsyncThunk('/bills/asyncGetBill', async () => {
	const res = await axios.get('http://localhost:8888/billsList')
	return res.data
})

export const asyncAddNewBill = createAsyncThunk('/bills/asyncAddNewBill', async (newBill) => {
	const res = await axios.post('http://localhost:8888/billsList', { ...newBill, id: nanoid() })
	return res.data
})

export default billsSlice.reducer


const getBillList = () => {
	return async (dispatch) => {
		const res = await axios.get('http://localhost:8888/billsList')
		dispatch(setBillList(res.data))
	}
}

const addNewBill = (newBill) => { 
	return async (dispatch) => {
		const res = await axios.post('http://localhost:8888/billsList', { ...newBill, id: nanoid() })
		dispatch(addBill(res.data))
	}
}

export { getBillList }